#! /usr/bin/bash

BRIGHT_FILE=/sys/class/backlight/amdgpu_bl0/brightness
MAX_BRIGHT_FILE=/sys/class/backlight/amdgpu_bl0/max_brightness
MAX_BRIGHT=$(/bin/cat $MAX_BRIGHT_FILE)

cur_bright=$(/bin/cat $BRIGHT_FILE)
cur_bright=$(calc -pd "_=config(\"display\", 0);$cur_bright / $MAX_BRIGHT * 100")

usage() {
    echo "Usage: $0 <0~100/i>"
    echo "       Set the brightness in percent to the specified value."
    echo "       The subcommand 'i' is for interactive usage."
    exit 0
}

adjust() {
    echo -e "$(calc -pd "_=config(\"display\", 0);$cur_bright/100 * $MAX_BRIGHT")" > $BRIGHT_FILE
}

adjust_with_retreat_print() {
    adjust
    # refs: https://en.wikipedia.org/wiki/ANSI_escape_code
    printf "\x1b[u\x1b[K\x1b[38;2;255;100;0m%s%%\x1b[0m\n" $cur_bright
}

PAT="0|([1-9][0-9]*)"

if [ $# -eq 0 ]; then
    # called with no argument
    printf "\x1b[38;2;100;100;255m%s\x1b[0m: \x1b[38;2;255;100;0m%s%%\x1b[0m\n" 'Current brightness' "$cur_bright"
    exit 0
elif [[ $1 = 'i' ]]; then
    # interactive mode
    printf "j: -1, J: -10\nk: +1, K: +10\nq: quit\n"
    printf "\x1b[38;2;100;100;255m%s\x1b[0m: \x1b[s\x1b[38;2;255;100;0m%s%%\x1b[0m\n" 'Current brightness' "$cur_bright"
    read -srn 1 inp
    while [ "$inp" != 'q' ]
    do
        case $inp in
            'j')
                if [ "$cur_bright" -gt 0 ]; then
                    cur_bright=$((cur_bright - 1))
                    adjust_with_retreat_print
                fi
                ;;
            'k')
                if [ "$cur_bright" -lt 100 ]; then
                    cur_bright=$((cur_bright + 1))
                    adjust_with_retreat_print
                fi
                ;;
            'J')
                if [ "$cur_bright" -gt 10 ]; then
                    cur_bright=$((cur_bright - 10))
                else
                    cur_bright=0
                fi
                adjust_with_retreat_print
                ;;
            'K')
                if [ "$cur_bright" -lt 90 ]; then
                    cur_bright=$((cur_bright + 10))
                else
                    cur_bright=100
                fi
                adjust_with_retreat_print
                ;;
        esac
        read -srn 1 inp
    done

    exit 0
elif [[ $1 =~ $PAT && $1 -ge 0 && $1 -le 100 ]]; then
    # the desired value is given
    cur_bright=$1
    adjust
else
    usage
fi
